#pragma once
#include "main.h"
#include <zephyr/random/random.h>

#include <ff.h>
#include <array>

#include <fcntl.h>
#include <unistd.h>

#define DISK_DRIVE_NAME "SD"
#define DISK_MOUNT_PT "/" DISK_DRIVE_NAME ":" // 挂载点"/SD:"
static const char *disk_mount_pt = DISK_MOUNT_PT;
uint8_t main_recoder_buf[5*512*10]={0};
void test_write_fs();



static FATFS fat_fs;
/* mounting info */
struct fs_mount_t mp = {
    .type = FS_FATFS,
    .fs_data = &fat_fs,
};

LOG_MODULE_REGISTER(main);

char mm[40961] = {0};
void test_write_name_fs(const char *name)
{
    const char *file_path = name;   // 文件路径，取决于挂载点
    string msg = "0123456789"; // 要写入的内容
    for (size_t i = 0; i < 4096; i++)
    {
       memcpy(&mm[i * 10], msg.c_str(), 10);
    }
    
    int fd = open(file_path, O_CREAT | O_WRONLY | O_TRUNC, 0666);
    if (fd < 0) {
        LOG_ERR("Failed to open file %s, error: %d", file_path, fd);
        return;
    }

    ssize_t written = write(fd, mm, strlen(mm));
    if (written < 0) {
        LOG_ERR("Write failed: %d  ,filename:%s", written,file_path);
    } else {
        LOG_INF("Written %d bytes to %s", written, file_path);
    }

    close(fd);  // 一定要关闭文件
   
}

class ay_fs_obj
{
private:
    /* data */
public:
    ay_fs_obj(/* args */);
    ~ay_fs_obj();
    void write_file(const char *filename, string &data, uint8_t is_append);
   void write_file_char(const char *filename, char* msg, uint8_t is_append);

    string read_file(const char *filename);

    void read_config_file();
    void write_config_file();
    long long int file_exists(const TCHAR *path);



};

ay_fs_obj::ay_fs_obj(/* args */)
{

    LOG_ERR("初始化文件系统: %s", DISK_MOUNT_PT);

    do
    {
        static const char *disk_pdrv = DISK_DRIVE_NAME;
        uint64_t memory_size_mb;
        uint32_t block_count;
        uint32_t block_size;

        if (disk_access_ioctl(disk_pdrv,
                              DISK_IOCTL_CTRL_INIT, NULL) != 0)
        {
            LOG_ERR("存储初始化失败");
            dev.err_code = -1;
            break;
        }

        if (disk_access_ioctl(disk_pdrv,
                              DISK_IOCTL_GET_SECTOR_COUNT, &block_count))
        {
            LOG_ERR("Unable to get sector count");
            break;
        }
        LOG_INF("Block count %u", block_count);

        if (disk_access_ioctl(disk_pdrv,
                              DISK_IOCTL_GET_SECTOR_SIZE, &block_size))
        {
            LOG_ERR("Unable to get sector size");
            break;
        }
        printk("Sector size %u\n", block_size);

        memory_size_mb = (uint64_t)block_count * block_size;
        printk("Memory Size(MB) %u\n", (uint32_t)(memory_size_mb >> 20));

        if (disk_access_ioctl(disk_pdrv,
                              DISK_IOCTL_CTRL_DEINIT, NULL) != 0)
        {
            LOG_ERR("Storage deinit ERROR!");
            break;
        }
    } while (0);

    mp.mnt_point = disk_mount_pt;
    int res = fs_mount(&mp);
    if (res != FR_OK)
    {
        LOG_INF("文件系统挂载失败");
        dev.err_code = -2;
        return;
    }

    LOG_INF("文件系统挂载成功");

    if (file_exists(AY_CONFIG_FILE)>=0)
    {
        LOG_INF("配置文件存在");

        read_config_file();
        dev.dev_count++;
        write_config_file();
        cout << "本次项目文件夹名称:" << dev.record_name << endl;



    }
    else
    {
        LOG_INF("新建默认配置文件");
        write_config_file();
        //  read_config_file();
    }


test_write_name_fs("/SD:/hello1.txt");


// test_write_name_fs("/SD:/hello5.txt");
// test_write_name_fs("/SD:/hello6.txt");
// test_write_name_fs("/SD:/hello7.txt");  
// test_write_name_fs("/SD:/hello8.txt");
// test_write_name_fs("/SD:/hello9.txt");
// test_write_name_fs("/SD:/hello10.txt");
// test_write_name_fs("/SD:/hello11.txt");
// test_write_name_fs("/SD:/hello12.txt");
// test_write_name_fs("/SD:/hello13.txt");
// test_write_name_fs("/SD:/hello14.txt");
// test_write_name_fs("/SD:/hello15.txt");
// test_write_name_fs("/SD:/hello16.txt");
// test_write_name_fs("/SD:/hello17.txt");
// test_write_name_fs("/SD:/hello18.txt");
// test_write_name_fs("/SD:/hello19.txt");
// test_write_name_fs("/SD:/hello20.txt");
// test_write_name_fs("/SD:/hello21.txt");
// test_write_name_fs("/SD:/hello22.txt");
// test_write_name_fs("/SD:/hello23.txt");
// test_write_name_fs("/SD:/hello24.txt");
// test_write_name_fs("/SD:/hello25.txt");
// test_write_name_fs("/SD:/hello26.txt");
// test_write_name_fs("/SD:/hello27.txt");
// test_write_name_fs("/SD:/hello28.txt");

}
extern ay_fs_obj *fs;

ay_fs_obj::~ay_fs_obj()
{
}
//////////////////基本读写
inline void ay_fs_obj::write_file(const char *filename, string &data, uint8_t is_append)
{

    // struct fs_file_t file;
    // int rc;

    // fs_file_t_init(&file);
    // if (is_append)
    // {
    //     rc = fs_open(&file, filename, FS_O_CREATE | FS_O_APPEND | FS_O_WRITE);
    // }
    // else
    // {
    //     rc = fs_open(&file, filename, FS_O_CREATE | FS_O_WRITE);
    // }
    // if (rc < 0)
    // {
    //     printk("打开文件:%s 失败: %d\n", filename, rc);
    //         fs_close(&file);

    //     return;
    // }

    // rc = fs_write(&file, data.c_str(), data.length());

    // if (rc < 0)
    // {
    //     printk("写入失败: %d\n", rc);
    // }

    // fs_close(&file);
    // fs_sync(&file);

    const char *file_path = filename;   // 文件路径，取决于挂载点
    const char *msg = data.c_str(); // 要写入文件的内容

    int fd = open(file_path, O_CREAT | O_WRONLY, 0666);
    if (fd < 0) {
        LOG_ERR("Failed to open file %s, error: %d", file_path, fd);
        return;
    }

    ssize_t written = write(fd, msg, strlen(msg));
    if (written < 0) {
        LOG_ERR("Write failed: %d", written);
    } else {
        LOG_INF("Written %d bytes to %s", written, file_path);
    }

    close(fd);  // 一定要关闭文件


}
inline void ay_fs_obj::write_file_char(const char *filename, char* msg, uint8_t is_append)
{



    const char *file_path = filename;   // 文件路径，取决于挂载点
    
    int fd = open(file_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
    if (fd < 0) {
        LOG_ERR("Failed to open file %s, error: %d", file_path, fd);
        dev.err_code = -2;
        return;
    }
           set_errcode(0);

    ssize_t written = write(fd, msg, strlen(msg));
    if (written < 0) {
        LOG_ERR("Write failed: %d", written);
    } else {
        LOG_INF("Written %d bytes to %s", written, file_path);
    }

    close(fd);  // 一定要关闭文件


}
inline string ay_fs_obj::read_file(const char *filename)
{

    struct fs_file_t file;
    int rc;
    string ret_data;
    fs_file_t_init(&file);
    rc = fs_open(&file, filename, FS_O_READ);
    if (rc < 0)
    {
        printk("读取文件:%s 失败: %d\n", filename, rc);
        return string();
    }
    int data_len =0 ;
    data_len = file_exists(filename);
    // 读取文件内容
    char *buffer = new char[data_len+1];
    buffer[data_len] = '\0';
    printk("read_file:读取文件大小是:%d+1\n",data_len);
    rc = fs_read(&file, buffer, data_len);
    if (rc < 0)
    {
        printk("读取失败: %d\n", rc);
    }
    else
    {
        ret_data = buffer;
    }
    fs_close(&file);
    return ret_data;
}

inline long long int ay_fs_obj::file_exists(const TCHAR *path)
{

    struct fs_dirent entry;
    int rc = fs_stat(path, &entry);
    if (rc == 0)
    {
        printk("文件:%s  大小: %u 字节\n", path, entry.size);
        return entry.size;
    }
    else
    {
        printk("获取文件:%s 信息失败: %d\n", path, rc);
        return -1;
    }
}


///////////////分割配置文件
std::vector<std::string> splitString(const std::string& str, const std::string& delim) {
    std::vector<std::string> tokens;
    size_t start = 0;
    //查找第一个分隔符的位置（str.find(delim)返回分隔符的起始索引，未找到则返回 npos）。
    size_t end = str.find(delim);
        // 使用循环查找所有分隔符并提取子字符串
    while (end != std::string::npos) {
        tokens.push_back(str.substr(start, end - start));
        start = end + delim.length();
        end = str.find(delim, start);
    }
    
    // Add the last segment
    tokens.push_back(str.substr(start));
    return tokens;
}

//////////////////配置读写

inline void ay_fs_obj::read_config_file()
{

    string config_data;
    config_data = read_file(AY_CONFIG_FILE);



    std::vector<std::string> parts = splitString(config_data, "|-|");

    for(const auto& part : parts) {
        cout << "Part: '" << part << "'" << endl;
    }

    dev.record_name = parts[0];
    dev.dev_mode = atoi(parts[1].c_str());
    dev.dev_count = atoi(parts[2].c_str());



//     int pos = config_data.find("|-|");
//     if (pos == string::npos) {
//         cout << "未找到分隔符，无效配置" << endl;
//         return;
//     }
//     // 提取第一部分（分隔符之前）
//     string part1 = config_data.substr(0, pos);
//   //  cout << "第一部分: '" << part1 << "'" << endl;
//        // 提取剩余部分（分隔符之后）
//     string remaining = config_data.substr(pos + 3); // 3是"|-|"的长度
//       //  cout << "第二部分: '" << remaining << "'" << endl;


        // dev.record_name = part1;
        // dev.dev_mode = atoi(remaining.c_str());
        // cout << "本次项目文件夹名称:"<< dev.record_name << endl;
        // cout << "设备模式: " << (int)dev.dev_mode << endl;

}

inline void ay_fs_obj::write_config_file()
{
    string config_data = dev.record_name + "|-|" + to_string(dev.dev_mode)+"|-|"+to_string(dev.dev_count);

    write_file(AY_CONFIG_FILE, config_data, 0);
}












//测试写入
std::string uint16_to_hex_manual(uint16_t value, bool uppercase = false) {
    constexpr char digits_lower[] = "0123456789abcdef";
    constexpr char digits_upper[] = "0123456789ABCDEF";
    const char* digits = uppercase ? digits_upper : digits_lower;

    std::array<char, 5> buffer{}; // 4字符 +逗号+ 1终止符
    buffer[0] = digits[(value >> 12) & 0xF]; // 高4位
    buffer[1] = digits[(value >> 8)  & 0xF];
    buffer[2] = digits[(value >> 4)  & 0xF];
    buffer[3] = digits[value         & 0xF];  // 低4位
    buffer[4] = ',';
    return std::string(buffer.data(), buffer.size()); // 避免终止符
}

// void test_write_fs()
// {
//   LOG_INF("开始测试写入文件系统");
//   uint16_t  num_tx;
//   string main_str;
//   for(int i=0;i<5000;i++)
//   {
// 	num_tx = (sys_rand32_get() % 65535) + 1;
//     string hex_str = uint16_to_hex_manual(num_tx,true);
//     main_str+=hex_str;
//     //LOG_INF("写入数据:%d: %s", i ,hex_str.c_str());
//   }
//   LOG_INF("测试结束,写入文本");

//    // printk("内容:%s",main_str.c_str());
  
//     fs->write_file(TEST_FILE, main_str, 0);


//     LOG_INF("测试结束,写入完毕");

//    // cout << "内容:" << main_str << endl;




   
// }


void test_write_fs()
{
    const char *file_path = "/SD:/hello.txt";   // 文件路径，取决于挂载点
    const char *msg = "Hello Zephyr POSIX!\n";

    int fd = open(file_path, O_CREAT | O_WRONLY | O_TRUNC, 0666);
    if (fd < 0) {
        LOG_ERR("Failed to open file %s, error: %d", file_path, fd);
        return;
    }

    ssize_t written = write(fd, msg, strlen(msg));
    if (written < 0) {
        LOG_ERR("Write failed: %d", written);
    } else {
        LOG_INF("Written %d bytes to %s", written, file_path);
    }

    close(fd);  // 一定要关闭文件
   
}

